package repostiory

import (
	"context"
	"gitee.com/chicken-c/go-learn/webook/internal/repostiory/cache"
)

var (
	ErrCodeSendTooMany        = cache.ErrCodeSendTooMany
	ErrCodeVerifyTooManyTimes = cache.ErrCodeVerifyTooManyTimes
)

type CodeRepository interface {
	Store(ctx context.Context, biz, phone, code string) error
	Verify(ctx context.Context, biz, phone, inputCode string) (bool, error)
}

type CachedCodeRepository struct {
	codeCache cache.CodeCache
}

func NewCachedCodeRepository(codeCache cache.CodeCache) CodeRepository {
	return &CachedCodeRepository{codeCache: codeCache}
}

func (repo *CachedCodeRepository) Store(ctx context.Context, biz, phone, code string) error {
	err := repo.codeCache.Set(ctx, biz, phone, code)
	if err == cache.ErrCodeSendTooMany {
		return ErrCodeSendTooMany
	}
	if err != nil {
		return err
	}

	return nil
}

func (repo *CachedCodeRepository) Verify(ctx context.Context, biz, phone, inputCode string) (bool, error) {
	bool, err := repo.codeCache.Verify(ctx, biz, phone, inputCode)
	if err == cache.ErrCodeVerifyTooManyTimes {
		return false, ErrCodeVerifyTooManyTimes
	}
	return bool, err
}
